'use strict';

angular.module('afasApp')
  .factory('authorization', ['$rootScope', '$state', 'principal', 'ServicesLS',
  function($rootScope, $state, principal, ServicesLS) {
    return {
      authorize: function() {
        return principal.identity()
          .then(function() {
            var isAuthenticated = principal.isAuthenticated();
            // console.log(isAuthenticated);

            // console.log($rootScope.toState.data.roles);
            // console.log(principal.isInAnyRole($rootScope.toState.data.roles));

            if (($rootScope.toState.data.roles && $rootScope.toState.data.roles.length > 0 && !principal.isInAnyRole($rootScope.toState.data.roles))) {
              if (isAuthenticated) {
                $state.go('home');
                // user is signed in but not authorized for desired state
              } else {
                // user is not authenticated. stow the state they wanted before you
                // send them to the signin state, so you can return them when you're done
                $rootScope.returnToState = $rootScope.toState;
                $rootScope.returnToStateParams = $rootScope.toStateParams;

                // now, send them to the signin state so they can log in
                var key = ServicesLS.get('_auth');
                if (typeof key === 'undefined' || key === null) {
                  $state.go('login');
                }

              }
            }
          });
      }
    };
  }
]);